package self.hoy.demo.cloud.nacos.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import self.hoy.demo.cloud.entities.CommonResult;
import self.hoy.demo.cloud.entities.Payment;
import self.hoy.demo.cloud.nacos.service.PaymentServiceImpl;

/**
 * @author 三共小不
 * @date 2020/6/16
 */
@Slf4j
@RestController
public class PaymentController {
    @Value("${server.port}")
    private String port;

    @Autowired
    private PaymentServiceImpl paymentService;

    @GetMapping("/payment/nacos/{id}")
    public String id(@PathVariable("id") Integer id) {
        return "nacos registry, server port is " + port + " id is " + id;
    }

    @GetMapping(value = "/echo/{string}")
    public String echo(@PathVariable String string) {
        System.out.println("========= provider ========= " + string + " ========");
        return "Hello Nacos Discovery " + string;
    }

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("{} insert {} result is {}", port, payment== null ? "" : payment.getSerial(), result);
        if (result > 0) {
            return new CommonResult(CommonResult.SUCCESS, port+"添加成功！", result);
        }
        return new CommonResult(CommonResult.FAIL, "");
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        Payment result = paymentService.getPaymentById(id);
        log.info("{} 查询Payment({})结果:{}", port, id, result);
        if (result == null) {
            return new CommonResult<Payment>(CommonResult.FAIL, null);
        }
        return new CommonResult<Payment>(CommonResult.SUCCESS, ""+port, result);
    }

    @GetMapping("/payment/timeout")
    public String timeout() {
        try {
            Thread.sleep(7000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return port;
    }
}
